import com.mit.web.business.proxy.ManufactureProxy;
import com.mit.web.business.remote.IInvokeResponder;
import com.mit.web.config.Constants;
import com.mit.web.event.PopWinCloseEvent;
import com.mit.web.model.manufacture.MOEnquiryModel;
import com.mit.web.util.LogUtil;
import com.mit.web.util.MessageUtil;
import com.mit.web.view.component.monitor.IProgressMonitor;
import com.mit.web.view.manufacture.MOCreationWindow;
import com.mit.web.view.manufacture.MOEditWindow;
import com.mit.web.vo.manufacture.MOVO;

import flash.events.MouseEvent;
import flash.ui.Mouse;

import flexlib.scheduling.util.DateUtil;

import mx.collections.ArrayCollection;
import mx.controls.PopUpMenuButton;
import mx.events.FlexEvent;
import mx.events.ListEvent;
import mx.events.MenuEvent;
import mx.logging.ILogger;
import mx.managers.PopUpManager;
import mx.rpc.events.ResultEvent;

private var _pm:IProgressMonitor;
private var _proxy:ManufactureProxy = ManufactureProxy.getInstance();
private var _logger:ILogger;
[Bindable] private var _model:MOEnquiryModel;

private function switchToAdvanceSearch(event:MouseEvent):void{
	txt_search.text = null;
	this.currentState='advSearch';
	var today:Date = new Date();
	dat_from.selectedDate = DateUtil.addTime(new Date(), -(DateUtil.MONTH_IN_MILLISECONDS));
	dat_to.selectedDate = today;
	cmb_factory.selectedIndex = -1;
	txt_code.text = null;
	
}

private function switchToQuickSearch(event:MouseEvent):void{
	
	dat_from.selectedDate = null;
	dat_to.selectedDate = null;
	cmb_factory.selectedIndex = -1;
	txt_code.text = null;
	this.currentState='basicSearch';
	txt_search.text = null;
}

protected function moStateMenuButtonCreationCompleteHandler(event:FlexEvent):void{
	var source:ArrayCollection = new ArrayCollection();
	var all:String = ResourceManager.getInstance().getString(Constants.BUNDLE_COMMON,"label.selectAll");
	source.addItem({label:all});
	source.addItem({type:"separator"});
	source.addAll(Constants.MO_STATES);
	(event.currentTarget as PopUpMenuButton).dataProvider = source;
}

private function doQuickSearch():void{
	_model.pageNo = 1;
	_model.code = txt_search.text;
	doEnquiry();
}

private function doAdvanceSearch(event:MouseEvent):void{
	_model.pageNo = 1;
	_model.factoryId = cmb_factory.selectedId;
	_model.dateFrom = dat_from.selectedDate;
	_model.dateTo = dat_to.selectedDate;
	_model.code = txt_code.text;
	doEnquiry();
}
private function newOrder(event:MouseEvent):void{
	var window:MOCreationWindow = new MOCreationWindow();
	window.addEventListener(PopWinCloseEvent.CREATED, createRecordHandler);
	PopUpManager.addPopUp(window,this,true);
	PopUpManager.centerPopUp(window);
}

private function createRecordHandler(event:PopWinCloseEvent):void{
	//新建的VO插入第一个元素
	var src:Array = _model.orderList.source;
	var newMo:MOVO = event.vo as MOVO;
	src.unshift(newMo);
	//如果一页满了就移除最后一个记录-- pending，it may be a bad behavior
	//src.pop();
	var updatedLst:ArrayCollection = new ArrayCollection(src);
	_model.orderList = updatedLst;
	dg.validateNow();
	//显示成功提示
	showMessageTip(event.msg, dg);
}

private function doFilter(event:MenuEvent):void{
	_model.pageNo = 1;
	_model.searchState = event.item.data;
	(event.currentTarget as PopUpMenuButton).label = event.label;
	doEnquiry();
}

private function doRefresh(event:MouseEvent):void{
	_model.code = null;
	_model.factoryId = 0;
	_model.dateFrom = null;
	_model.dateTo = null;
	_model.pageNo = 1;
	_model.searchState = null;
	doEnquiry();
	
}

private function datagridCreationCompleteHanlder(event:FlexEvent):void{
	_logger = LogUtil.getLogger(this);
	_logger.debug("DataGrid created, load all records");
	
	_model = new MOEnquiryModel();
	doEnquiry();
}

private function goToPage(pageNo:int):void{
	_model.pageNo = pageNo;
	doEnquiry();
}

private function doEnquiry():void{
	//读取记录集
	var r1:IInvokeResponder = _proxy.getPagedMO(_model.pageNo, _model.code,  _model.factoryId
		, _model.dateFrom, _model.dateTo, _model.searchState);
	r1.addResultListener(retrieveListHandler);
	r1.addFaultListener(exceptionHandler);
	
	var r2:IInvokeResponder = _proxy.getMOCount(_model.code,  _model.factoryId, _model.dateFrom
		, _model.dateTo, _model.searchState);
	r2.addResultListener(retrieveRCHandler);
	r2.addFaultListener(exceptionHandler);
}

private function retrieveListHandler(event:ResultEvent):void{
	var lst:ArrayCollection = event.result as ArrayCollection;
	//有记录返回才更新，否则只是提示无记录存在
	if(lst != null && lst.length > 0){
		_model.orderList = lst;
		//dg.validateNow();
	}
	else
		MessageUtil.popNoRecordMessage(this);
}

private function retrieveRCHandler(event:ResultEvent):void{
	var rc:int = event.result as int;
	//与取回记录的行为保持一致，如果没有记录找到，不做任何动作。
	if(rc > 0){
		_logger.debug("Total record: " + rc.toString());
		_model.recordCount = rc;
	}
}

private function doEdit(event:ListEvent):void{
	var selectedMO:MOVO = _model.orderList[event.rowIndex] as MOVO;
	var id:int = selectedMO.id;
	var window:MOEditWindow = new MOEditWindow();
	window.addEventListener(PopWinCloseEvent.SAVED, updateRecordHandler);
	window.addEventListener(PopWinCloseEvent.DELETED, deleteRecordHandler);
	window.orderId = id;
	window.title = selectedMO.code;
	PopUpManager.addPopUp(window,this,true);
	PopUpManager.centerPopUp(window);
}

private function updateRecordHandler(event:PopWinCloseEvent):void{
	var savedMO:MOVO = event.vo as MOVO;
	_model.orderList[dg.selectedIndex] = savedMO;
	dg.validateNow();
	//显示成功提示
	showMessageTip(event.msg, dg);
}

private function deleteRecordHandler(event:PopWinCloseEvent):void{
	_model.orderList.removeItemAt(dg.selectedIndex);
	dg.validateNow();
	//显示成功提示
	showMessageTip(event.msg, dg);
}

